//
//  YTNetworkManager.m
//  yitaicaijing
//
//  Created by DIANGHONG on 2018/7/9.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "YTNetworkManager.h"
#import <CFNetwork/CFNetwork.h>
#define kMainUrlStr @"http://api.etaicj.com/"
#define kTestMainUrl @"http://api.1yge.com/"
// 网络请求工具类
@implementation YTNetworkManager


+ (instancetype)shareManager{
    
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[YTNetworkManager alloc] init];
        
        [(YTNetworkManager *)instance setTextSize:100];
        
        [(YTNetworkManager *)instance responseSerializer].acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"application/javascript", nil];
        [(YTNetworkManager *)instance requestSerializer].timeoutInterval = 60;
            
    });
    return instance;
}



- (YTUserAccount *)account
{
    if (!_account) {
        _account = [[YTUserAccount alloc] init];
        if (!_account.auth) {
            // FIXME: - token没值 重新登录
            return _account;
        }
        [self.requestSerializer setValue:_account.auth forHTTPHeaderField:@"user-token"];
    }
    return _account;
}

/*
 封装上传数据的方法
 */
- (void)uploadWithUrlString:(NSString *)urlString data:(NSData *)data name:(NSString *)name params:(NSDictionary *)params completion:(void(^)(id json, BOOL isSuccess))completion
{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",kMainUrlStr,urlString];
    
    //post请求
    [self POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //拼接结构体
        [formData appendPartWithFileData:data name:name fileName:@"user_avatar.png" mimeType:@"image/png"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        completion(responseObject,true);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        completion(nil , false);
        
    }];
}

/**
 用一个函数网络封装请求GET、POST的方法
 
 @param method 请求方法 GET/POST
 @param urlStr url
 @param params 参数
 @param completion 完成回调
 */
- (void)requestWithMethod:(MethodHTTP)method
                UrlString:(NSString *)urlStr
                   params:(NSDictionary *)params
               completion:(void(^)(id json ,BOOL isSuccess))completion
{
    NSString *url = [NSString stringWithFormat:@"%@%@",kMainUrlStr,urlStr];
    
    
    // 成功回调
    void(^successful)(id, NSURLSessionDataTask *) = ^(id response, id task){
        
        
        if ([task[@"code"] intValue] == -888) {
            [self.requestSerializer setValue:nil forHTTPHeaderField:@"access-token"];
            CFUUIDRef cfuuid = CFUUIDCreate(kCFAllocatorDefault);
            NSString *device_id = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, cfuuid));
            NSString *rand_str = [NSString return16LetterAndNumber];
            NSString *timestamp = [self currentTimeStr];
            
            NSString *signature = [self signatureWithDevice_id:device_id
                                                      rand_str:rand_str
                                                     timestamp:timestamp];
            
            // 获取aceessToken
            [self requestAccessWithSignature:signature
                                            device_id:device_id
                                            rand_str:rand_str
                                            timestamp:timestamp
                                            completion:^(BOOL isSucc, NSString *error)
             {
                 if (!isSucc) {
                     return ;
                 }
                 
             }];
        }
        
        completion(task,true);
    };
    
    // 是失败回调
    void(^requestFailure)(NSURLSessionDataTask *, NSError *) = ^(NSURLSessionDataTask *task, NSError *error){


        //FIXME: 网络请求失败
        NSLog(@"失败---%@",error);
        
        completion(nil,false);
    };
    
    
    if (method == MethodGet)
    {
        [self GET:url parameters:params progress:nil success:successful failure:requestFailure];
        
    }else
    {
        [self POST:url parameters:params progress:nil success:successful failure:requestFailure];
    }
    
}



#pragma mark: - 查询是否设置了代理
- (BOOL) checkProxySetting
{
    NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
    NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"https://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
    NSLog(@"\n%@",proxies);
    
    NSDictionary *settings = proxies[0];
    NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyHostNameKey]);
    NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
    NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyTypeKey]);
    
    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"])
    {
        NSLog(@"没设置代理");
        return NO;
    }
    else
    {
        
        NSLog(@"设置了代理");
        return YES;
    }
    
}


- (void)getAccessTokeWithCompletion:(void(^)(BOOL isSucc, NSString *error))completion
{
    CFUUIDRef cfuuid = CFUUIDCreate(kCFAllocatorDefault);
    NSString *device_id = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, cfuuid));
    NSString *rand_str = [NSString return16LetterAndNumber];
    NSString *timestamp = [self currentTimeStr];
    
    NSString *signature = [self signatureWithDevice_id:device_id rand_str:rand_str timestamp:timestamp];
    
    [self requestAccessWithSignature:signature
                           device_id:device_id
                            rand_str:rand_str
                           timestamp:timestamp
                          completion:completion];
}





//获取当前时间戳
- (NSString *)currentTimeStr
{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];  // *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

// 加签名的方法
- (NSString *)signatureWithDevice_id:(NSString *)device_id
                            rand_str:(NSString *)rand_str
                           timestamp:(NSString *)timestamp
{
    NSString *signatureStr = [NSString stringWithFormat:@"app_id=%@&app_secret=%@&device_id=%@&rand_str=%@&timestamp=%@",kApp_ID,kApp_Secret,device_id,rand_str,timestamp];
    
    
    return [signatureStr md5];
}

@end
